﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Organizations;
using Camc.Quality.Authorization.Roles;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Inspection.InspectionBoard;
using Camc.Quality.Inspection.InspectionStrat;
using Camc.Quality.Quality;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Camc.Quality.Inspection
{
    public class InspectionBoardAppService : QualityAppServiceBase
    {
        private readonly IRepository<InspectionSeverityDesc, Guid> _inspectionSeverityDescRepository;
        private readonly IRepository<InspectionTypeDesc, Guid> _inspectionTypeDescRepository;
        private readonly IRepository<InspectionItemInfo, Guid> _inspectionItemInfoRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<InspectionStandardDesc, Guid> _inspectionStandardDescRepository;
        private readonly RoleManager _roleManager;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<UserRole, long> _userRoleRepository;
        public readonly IRepository<UploadPicture, Guid> _uploadPictureRepository;

        public InspectionBoardAppService(IRepository<InspectionSeverityDesc, Guid> inspectionSeverityDescRepository,
                             IRepository<InspectionTypeDesc, Guid> inspectionTypeDescRepository,
                             IRepository<InspectionItemInfo, Guid> inspectionItemInfoRepository,
                             IRepository<OrganizationUnit, long> organizationUnitRepository,
                             RoleManager roleManager,
                             IRepository<InspectionStandardDesc, Guid> inspectionStandardDescRepository,
                             IRepository<User, long> userRepository,
                             IRepository<UserRole, long> UserRoleRepository,
                             IRepository<UploadPicture, Guid> uploadPictureRepository
                                    )
        {
            _inspectionSeverityDescRepository = inspectionSeverityDescRepository;
            _inspectionTypeDescRepository = inspectionTypeDescRepository;
            _inspectionItemInfoRepository = inspectionItemInfoRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _roleManager = roleManager;
            _inspectionStandardDescRepository = inspectionStandardDescRepository;
            _userRepository = userRepository;
            _userRoleRepository = UserRoleRepository;
            _uploadPictureRepository = uploadPictureRepository;
        }
        /// <summary>
        /// 异常严重度分布
        /// </summary>
        /// <returns></returns>
        public async Task<InspectionSeverityDataDto> GetInepectionBoardTitle()
        {
            var inspectionStardardDesc = _inspectionStandardDescRepository.GetAll();
            int totProcessing = inspectionStardardDesc.Where(s => s.State != States.未处理).Count();
            int processing = inspectionStardardDesc.Where(s => s.State != States.未处理 && s.State != States.已完成).Count();
            var severityDesc = _inspectionSeverityDescRepository.GetAll().Where(d => d != null && d.IsUsed == InspectionSeverityDesc.IsUseds.启用);
            InspectionSeverityDataDto inspectionSeverityDataDto = new InspectionSeverityDataDto()
            {
                NotProcessing = totProcessing,
                Processing = processing
            };
            List<string> severity = new List<string>();
            List<int> quantity = new List<int>();
            foreach (var item in severityDesc)
            {
                int count = inspectionStardardDesc.Where(s => s.InspectionSeverityDescId == item.Id).Count();
                if (count != 0)
                {
                    severity.Add(item.SeverityName);
                    quantity.Add(count);
                    inspectionSeverityDataDto.Severity = severity;
                    inspectionSeverityDataDto.Quantity = quantity;
                }
            }
            return inspectionSeverityDataDto;
        }
        /// <summary>
        /// 当前异常分布
        /// </summary>
        /// <returns></returns>
        public async Task<List<InspectionDistributionDto>> GetInspectionDistributionDto()
        {
            var inspectionStardardDesc = _inspectionStandardDescRepository.GetAll().Where(s => s.State != States.已完成);
            var inspectionTypeDesc = _inspectionTypeDescRepository.GetAll().Where(d => d != null && d.IsUsed != InspectionTypeDesc.IsUseds.已删除);
            var inspectionItemInfo = _inspectionItemInfoRepository.GetAll().Where(d => d != null && d.IsUsed != InspectionItemInfo.IsUseds.已删除).ToList();
            int totalCount = inspectionStardardDesc.Count();
            List<InspectionDistributionDto> inspectionDistributionDtos = new List<InspectionDistributionDto>();
            foreach (var item in inspectionItemInfo)
            {
                inspectionStardardDesc = inspectionStardardDesc.Where(s => s.InspectionItemInfoId == item.Id);
                int count = inspectionStardardDesc.Count();
                InspectionDistributionDto inspectionDistributionDto = new InspectionDistributionDto();
                var typeDesc = inspectionTypeDesc.FirstOrDefault(s => s.Id == item.TypeId);
                if (typeDesc != null)
                {
                    inspectionDistributionDto.InspectionDetils = item.ItemName + "-" + typeDesc.TypeName + "（" + count + "）";
                }
                else
                {
                    inspectionDistributionDto.InspectionDetils = item.ItemName + "（" + count + "）";
                }
                if (totalCount != 0)
                {
                    inspectionDistributionDto.Percent = count / totalCount * 100;
                }
                else
                {
                    inspectionDistributionDto.Percent = 0;
                }
                inspectionDistributionDtos.Add(inspectionDistributionDto);
            }
            inspectionDistributionDtos.OrderByDescending(s => s.Percent);
            return inspectionDistributionDtos;
        }
        /// <summary>
        /// 当前异常
        /// </summary>
        /// <returns></returns>
        public List<InspectionDistributionlistDto> GetInspectionDistributionlist()
        {
            List<InspectionDistributionlistDto> inspectionDistributionlistDtos = new List<InspectionDistributionlistDto>();
            var query = _inspectionStandardDescRepository.GetAll().Where(s => s.State != States.已完成);
            if (query.Count() > 0)
            {
                var queryData = query.OrderByDescending(e => e.CreationTime).ToList();
                string url = ConfigHelper.GetAppSetting("App", "GetAppUrl") + "/Inspection/";
                for (int i = 0; i < queryData.Count(); i++)
                {
                    InspectionDistributionlistDto inspectionDistributionlistDto = new InspectionDistributionlistDto();
                    inspectionDistributionlistDto.Id = queryData[i].Id;
                    inspectionDistributionlistDto.State = (int)queryData[i].State;
                    var inspectionType = _inspectionTypeDescRepository.FirstOrDefault(s => s.Id == queryData[i].InspectionTypeDescId);
                    var inspectionItemInfo = _inspectionItemInfoRepository.FirstOrDefault(s => s.Id == queryData[i].InspectionItemInfoId);
                    var InspectionSeverity = _inspectionSeverityDescRepository.FirstOrDefault(s => s.Id == queryData[i].InspectionSeverityDescId);
                    var typeName = "";
                    var itemName = "";
                    if (inspectionType != null) typeName = inspectionType.TypeName;
                    if (inspectionItemInfo != null) itemName = inspectionItemInfo.ItemName;
                    inspectionDistributionlistDto.Name = typeName + "-" + itemName;
                    inspectionDistributionlistDto.InspectionDetails = queryData[i].InspectionDetails;
                    if (InspectionSeverity != null) inspectionDistributionlistDto.InspectionSeverityDesc = InspectionSeverity.SeverityName;
                    var createUser = _userRepository.FirstOrDefault(s => s.Id == queryData[i].CreatorUserId);
                    var handler = _userRepository.FirstOrDefault(s => s.Id == queryData[i].HandlerId);
                    if (createUser != null) inspectionDistributionlistDto.Submitter = createUser.Surname + createUser.Name;
                    if (handler != null) inspectionDistributionlistDto.Handler = handler.Surname + handler.Name;
                    //查询上传图片信息
                    var flieList = (from up in _uploadPictureRepository.GetAll().Where(s => s.BusinessId == queryData[i].Id)
                                    select new UploadPicture
                                    {
                                        Id = up.Id,
                                        CreationTime = up.CreationTime,
                                        CreatorUserId = up.CreatorUserId,
                                        FileName = up.FileName,
                                        FileUrl = url + up.FileName,
                                        Size = up.Size
                                    }).ToList();
                    foreach (var item in flieList)
                    {
                        if (item.FileUrl.Contains(".jpg"))
                        {
                            item.FileUrl = item.FileUrl.Replace(".jpg", "_thumbnail.jpg");
;                        }
                        if (item.FileUrl.Contains(".jpeg"))
                        {
                            item.FileUrl = item.FileUrl.Replace(".jpeg", "_thumbnail.jpeg");
                        }
                        if (item.FileUrl.Contains(".png"))
                        {
                            item.FileUrl = item.FileUrl.Replace(".png", "_thumbnail.png");
                        }
                    }
                    if (flieList != null)
                    {
                        var flieResult = ObjectMapper.Map<List<InspectionFileUploadDto>>(flieList.ToList());
                        inspectionDistributionlistDto.InspectionFileUploadDto = flieResult.ToList();
                    }
                    inspectionDistributionlistDtos.Add(inspectionDistributionlistDto);
                }
                return inspectionDistributionlistDtos;
            }
            else
            {
                return new List<InspectionDistributionlistDto>();
            }
        }
}
}
